﻿using ColorApplication.Helper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace ColorApplication
{
    public partial class CreateTransaction : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            myPage.Text = createMPITransaction();
        }

        private String createMPITransaction()
        {
            string terminal_id = ConfigurationManager.AppSettings["TerminalId"];
            string merchant_id = ConfigurationManager.AppSettings["MerchantId"];
            string amount = (Math.Round(getPrice(), 2) * 100).ToString("#0");//ConfigurationManager.AppSettings["Amount"];
            string user = ConfigurationManager.AppSettings["User"];
            string password = ConfigurationManager.AppSettings["Password"];
            string cg_gateway_url = ConfigurationManager.AppSettings["CG_Gateway_Url"];
            string currency = ConfigurationManager.AppSettings["Currency"];
            //string terminal_id = "0962922";
            //string merchant_id = "1";
            //string amount = "1500050";
            //string user = "israel";
            //string password = "Israeli1.";
            //string cg_gateway_url = "https://cguat2.creditguard.co.il/xpo/Relay";


            Random rand = new Random();
            string uniqueID = DateTime.Now.ToString("yyyyddMM") + rand.Next(0, 1000);
            String result = "";
            String poststring = "user=" + user +
                                  "&password=" + password +
                                  "&int_in=<ashrait>" +
                                     "<request>" +
                                      "<version>1000</version>" +
                                      "<language>ENG</language>" +
                                      "<dateTime/>" +
                                      "<command>doDeal</command>" +
                                      "<doDeal>" +
                                           "<terminalNumber>" + terminal_id + "</terminalNumber>" +
                                           "<mainTerminalNumber/>" +
                                           "<cardNo>CGMPI</cardNo>" +
                                           "<total>" + amount + "</total>" +
                                           "<transactionType>Debit</transactionType>" +
                                           "<creditType>RegularCredit</creditType>" +
                                           "<currency>" + currency + "</currency>" +
                                           "<transactionCode>Phone</transactionCode>" +
                                           "<authNumber/>" +
                                           "<numberOfPayments/>" +
                                           "<firstPayment/>" +
                                           "<periodicalPayment/>" +
                                           "<validation>TxnSetup</validation>" +
                                           "<dealerNumber/>" +
                                           "<user>something</user>" +
                                           "<mid>" + merchant_id + "</mid>" +
                                           "<uniqueid>" + uniqueID + "</uniqueid>" +
                                           "<mpiValidation>autoComm</mpiValidation>" +
                                           "<email></email>" +
                                           "<clientIP/>" +
                                           "<customerData>" +
                                            "<userData1/>" +
                                            "<userData2/>" +
                                            "<userData3/>" +
                                            "<userData4/>" +
                                            "<userData5/>" +
                                            "<userData6/>" +
                                            "<userData7/>" +
                                            "<userData8/>" +
                                            "<userData9/>" +
                                            "<userData10/>" +
                                           "</customerData>" +
                                           "<returnUrl>http://www.colorsay.com/FileUpload.aspx</returnUrl>" +
                                           "<cancelUrl>http://www.colorsay.com/FileUpload.aspx</cancelUrl>" +
                                      "</doDeal>" +
                                     "</request>" +
                                    "</ashrait>";


            StreamWriter myWriter = null;

            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(cg_gateway_url);
            objRequest.Method = "POST";
            objRequest.ContentLength = poststring.Length;
            objRequest.ContentType = "application/x-www-form-urlencoded";

            try
            {
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(poststring);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                if (myWriter != null)
                    myWriter.Close();
            }

            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader sr =
               new StreamReader(objResponse.GetResponseStream()))
            {
                result = sr.ReadToEnd();

                // Close and clean up the StreamReader
                sr.Close();
            }


            XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);

            XmlNodeList Nodes = doc.GetElementsByTagName("mpiHostedPageUrl");
            string response = Nodes[0].InnerText;
            return "<script>window.location='" + response + "';</" + "script>";
        }

        public decimal getPrice()
        {
            SqlDataReader dr;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {

                SqlParameter[] parameter = { new SqlParameter("@Id", null) };
                SqlCommand cmd = SQLHelper.GetCommand(con, "GetWhiteColorNeutralizationSelect", parameter);
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["Price"] != DBNull.Value)
                        return Convert.ToDecimal(dt.Rows[0]["Price"]);
                }
                return 0;
            }
        }
    }
}